/**
 * Copyright &copy; 2012-2016 <a href="https://www.kaaction.com">KAA</a> All rights reserved All rights reserved.
 */
package com.kaaction.modules.market.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.kaaction.common.config.Global;
import com.kaaction.common.persistence.Page;
import com.kaaction.common.web.BaseController;
import com.kaaction.common.utils.StringUtils;
import com.kaaction.common.utils.WechatUtils;
import com.kaaction.common.utils.ZxingHandler;
import com.kaaction.modules.market.entity.Event;
import com.kaaction.modules.market.entity.EventChannel;
import com.kaaction.modules.market.service.EventChannelService;
import com.kaaction.modules.market.service.EventService;
import com.kaaction.modules.operate.entity.Channel;
import com.kaaction.modules.operate.service.ChannelService;

/**
 * 活动Controller
 * @author zengbiao
 * @version 2017-04-22
 */
@Controller
@RequestMapping(value = "${adminPath}/market/event")
public class EventController extends BaseController {

	@Autowired
	private EventService eventService;
	
	@Autowired
	private EventChannelService eventChannelService;
	
	@Autowired
	private ChannelService channelService;
	
	private final static String QRCODE_PATH = "/dynamic/images/event/"; 
	
	@ModelAttribute
	public Event get(@RequestParam(required=false) String id) {
		Event entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = eventService.get(id);
		}
		if (entity == null){
			entity = new Event();
		}
		return entity;
	}
	
	@RequiresPermissions("market:event:view")
	@RequestMapping(value = {"list", ""})
	public String list(Event event, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Event> page = eventService.findPage(new Page<Event>(request, response), event); 
		model.addAttribute("page", page);
		return "modules/market/eventList";
	}

	@RequiresPermissions("market:event:view")
	@RequestMapping(value = "form")
	public String form(Event event, Model model) {
		
		if (!StringUtils.isBlank(event.getId())) {
			List<EventChannel> eventChannelList = eventChannelService.findListByEventId(event.getId());
			String channelIds = "";
			for(EventChannel ins : eventChannelList){
				channelIds += ("," + ins.getChannel().getId());
			}
			event.setChannelIds(channelIds);;
		}
		//生成树状结构的渠道列表
		model.addAttribute("channelList", channelService.findList(new Channel()));
		
		model.addAttribute("event", event);
		return "modules/market/eventForm";
	}

	@RequiresPermissions("market:event:edit")
	@RequestMapping(value = "save")
	public String save(HttpServletRequest request, Event event, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, event)){
			return form(event, model);
		}
		
		String coverImage = event.getCoverImage();
		String moreImage = event.getMoreImages();
		if(!StringUtils.isBlank(coverImage)){
			coverImage = coverImage.replace("|", Global.getPicPrefix());
			event.setCoverImage(coverImage);
		}
		if(!StringUtils.isBlank(moreImage)){
			moreImage = moreImage.replace("|", Global.getPicPrefix());
			event.setMoreImages(moreImage);
		}
		eventService.save(event);
		
		//TODO: 应当移植到业务层，一个事务中
				if(event != null && !StringUtils.isBlank(event.getId())){
					//1.delete all related records
					eventChannelService.deleteByEventId(event.getId());;
					
					String channelIds = event.getChannelIds();
					//2.add 
					if(!StringUtils.isBlank(channelIds) && channelIds.indexOf(",") != -1){
						String[] channelIdArr = channelIds.split(",");
						for(String channelIdStr : channelIdArr) {
							EventChannel eventChannel = new EventChannel();
							if(!StringUtils.isBlank(channelIdStr)){
								eventChannel.setEventId(event.getId());
								Channel channel = new Channel();
								channel.setId(channelIdStr);
								eventChannel.setChannel(channel);
								//TODO 定义基础活动的根地址
								String requestUrl = request.getScheme() //当前链接使用的协议
									    +"://" + request.getServerName()//服务器地址 
									    + ":" + request.getServerPort(); //端口号 
								String eventPath = "http://www.kaaction.com/show/kaa"+event.getType()+".html";
								String pagePathWithWeixinToken = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WechatUtils.APP_ID
								+"&redirect_uri="+eventPath
								+"&response_type=code&scope=snsapi_base&state="+event.getId() + "~" + channelIdStr
								+"#wechat_redirect";
								logger.info("二维码的链接地址:" + pagePathWithWeixinToken);
								String tomcatPath = request.getSession().getServletContext().getRealPath("") ;
								String qrcodePath = ZxingHandler.createQrcode(pagePathWithWeixinToken, 400, 400, tomcatPath + QRCODE_PATH);
								logger.info("二维码图片在服务器位置:" + tomcatPath + QRCODE_PATH);
								int loc = qrcodePath.lastIndexOf("/");
								qrcodePath = qrcodePath.substring(loc + 1);
								logger.info("数据库表(eventchannel)中，记录二维码图片:" + requestUrl + request.getContextPath() + QRCODE_PATH + qrcodePath);
								eventChannel.setQrcode(requestUrl + request.getContextPath() + QRCODE_PATH + qrcodePath);
								eventChannel.setDelFlag("0");
								eventChannelService.save(eventChannel);
							}
						}
					}
				}
				
		
		addMessage(redirectAttributes, "保存活动成功");
		return "redirect:"+Global.getAdminPath()+"/market/event/?repage";
	}
	
	@RequiresPermissions("market:event:edit")
	@RequestMapping(value = "delete")
	public String delete(Event event, RedirectAttributes redirectAttributes) {
		eventService.delete(event);
		addMessage(redirectAttributes, "删除活动成功");
		return "redirect:"+Global.getAdminPath()+"/market/event/?repage";
	}

}